/*
 * 
 * Author: Philipp Tarasiewicz
 * 
 */

var websocketGame = { };

websocketGame.cards				= [];
websocketGame.img				= {};
websocketGame.running			= false;
websocketGame.authHeader		= prompt("Please enter an 'Authorization' header value.", "cGhpbDplMTIwZWEyODBhYTUwNjkzZDU1NjhkMDA3MTQ1NjQ2MA==");
websocketGame.thisPlayerId		= prompt("Are you player 1 or player 2?", "1");
websocketGame.otherPlayerId		= 0;
websocketGame.thisPlayersTurn	= false;
websocketGame.resumeRequired	= false;
websocketGame.cfg				= new TCGConfig();
websocketGame.protocol			= new TCGProtocol();



// init script when the DOM is ready.
$(function() {
	
	// clone 5 duplicates of the card
	for(var i = 0; i < 5; i++) {
		$(".card:first-child").clone().appendTo("#cards");
	}

	// initialize each card's position
	$("#cards").children().each(function(index) {
		
		var idx = index % 3;
		
		// align the cards to be 3x2
		$(this).css({
			"left" : ($(this).width() + 30) * idx,
			"top" : ($(this).height() + 30) * Math.floor(index / 3)
		});
		
		$(this).attr("data-index", idx);
		$(this).attr("data-cid", 0);
		
		if (index > 2) {
			$(this).attr("data-pid", websocketGame.thisPlayerId);
		}
		else {
			$(this).attr("data-pid", 0);
		}
		

		// get a pattern from the shuffled deck
		//var pattern = matchingGame.deck.pop();
		// visually apply the pattern on the card's back side.
		//$(this).find(".back").addClass(pattern);
		// embed the pattern data into the DOM element.
		//$(this).attr("data-pattern", pattern);
		// listen the click event on each card DIV element.
		
		
		$(this).click(function() {
			onCardClick(this);
		});


		
	});
	
	/* ######################################################## */
	/* ######################################################## */
	/* ######################################################## */
	
	// check existence of WebSockets in browser
	if (!"WebSocket" in window) {
		alert("Your browser does not support web sockets.  Please try another browser.");
	}
	else {
		// create connection
		websocketGame.socket = new WebSocket("ws://" + websocketGame.cfg.getIP() + ":8888/game");
		
		// on open event
		websocketGame.socket.onopen = function(e) {
			console.log('WebSocket connection established.');
			
			websocketGame.socket.send('{"subject":"game-j","l":"de-DE","j":{"gameId":11,"playerId":' + websocketGame.thisPlayerId + ',"otp":"123asd"}}');
		};
		
		// on message event
		websocketGame.socket.onmessage = function(e) {
			console.log(e.data);
			websocketHandleMessage( jQuery.parseJSON(e.data) );
		};
		
		// on close event
		websocketGame.socket.onclose = function(e) {
			console.log('WebSocket connection closed.');
			websocketHandleClose();
		};
	}
});

function onCardClick(cardTarget) {
	console.log("Clicked on card " + $(cardTarget).attr("data-cid"));
	
	if (websocketGame.resumeRequired) {
		websocketGame.socket.send( websocketGame.protocol.getResumeMsg() );
		return;
	}
	
	if (!websocketGame.running || $(cardTarget).attr("data-pid") == websocketGame.thisPlayerId) {
		$(cardTarget).toggleClass("card-flipped");
	}
	else {
		if ( websocketGame.thisPlayersTurn && $(cardTarget).attr("data-pid") != websocketGame.thisPlayerId ) {
			$('#cards div.card[data-pid="' + websocketGame.thisPlayerId + '"]').each(function() {
				if ( $(this).find(".back").css('backgroundColor') == "rgb(255, 255, 0)" ) {
					$(this).find(".back").css('backgroundColor', 'white');
				}
			});
			
			var slot = $(cardTarget).attr("data-index");
			var select = websocketGame.protocol.getSelectMsg(slot);
			websocketGame.socket.send(select);
		}
	}
}

function websocketHandleMessage(data) {
	if ( is(data) && is(data.subject) ) {
		if (data.subject == "game-j") {
			handleGameJoinMsg(data.j);
		}
		else if (data.subject == "game-i") {
			handleGameInfoMsg(data.i);
		}
		else if (data.subject == "game-p") {
			handleGameProgressMsg(data.p);
		}
		else {
			console.log("Unknown subject:" + data.subject);
		}
	}
	else {
		console.log("Invalid WebSocket message!");
	}
}

function handleGameJoinMsg(j) {
	if ( is(j) && is(j.code) ) {
		if ( j.code == 200 ) {
			console.log("Successfully joined the game!");
		}
		else {
			console.log("Couldn't join the game: " + j.code);
		}
	}
	else {
		console.log("Invalid game join response!");
	}
}

function handleGameInfoMsg(i) {
	if ( is(i) && is(i.key) && i.key == "g_start" ) {
		websocketGame.running = true;
		onGameStart();
	}
}

function handleGameProgressMsg(p) {
	websocketGame.thisPlayersTurn 	= false;
	websocketGame.resumeRequired	= false;
	
	if ( is(p) && is(p.cmd) ) {
		if (p.cmd == "select") {
			websocketGame.thisPlayersTurn = true;
			
			$('#cards div.card[data-pid="' + websocketGame.otherPlayerId + '"]').each(function() {
				if ( $(this).find(".back").css('backgroundColor') == "rgb(255, 255, 0)" ) {
					$(this).find(".back").css('backgroundColor', 'white');
				}
			});
			
			$('#cards div.card[data-pid="' + websocketGame.thisPlayerId + '"][data-index="' + p.s + '"]').find(".back").css('backgroundColor', 'yellow');
		}
		else if (p.cmd == "resume") {
			//alert("Please resume the game!");
			
			$('#cards div.card[data-pid="' + websocketGame.otherPlayerId + '"]').each(function() {
				if ( $(this).find(".back").css('backgroundColor') == "rgb(255, 255, 0)" ) {
					$(this).find(".back").css('backgroundColor', 'white');
				}
			});
			
			console.log("Resume required!");
			websocketGame.resumeRequired = true;
		}
		else if (p.cmd == "wait") {
			//alert("Please resume the game!");
			console.log("Waiting for opponent's selection!");
			$('#cards div.card[data-pid="' + websocketGame.otherPlayerId + '"][data-index="' + p.s + '"]').find(".back").css('backgroundColor', 'yellow');
		}
		else {
			console.log("Unknown progress cmd!");
		}
	}
	else if ( is(p.winner) ) {
		console.log("Winner is: " + p.winner);
	}
	else if ( is(p.s) && is(p.pId) && is(p.cId) ) {
		var obj = null;
		
		if ( is( websocketGame.cards[p.pId] ) ) {
			if ( is(websocketGame.cards[p.pId][p.s]) ) {
				obj = websocketGame.cards[p.pId][p.s];
			}
			else {
				websocketGame.cards[p.pId][p.s] = {};
				obj = websocketGame.cards[p.pId][p.s];
			}
		}
		else {
			websocketGame.cards[p.pId] = [];
			websocketGame.cards[p.pId][p.s] = {};
			obj = websocketGame.cards[p.pId][p.s];
		}
		
		obj.cId		= p.cId;
		obj.pIds 	= p.pIds;
		obj.l 		= p.l;
		obj.at 		= p.at;
		obj.d 		= p.d;
		obj.ag 		= p.ag;
		
		onGameCardProgress(p.pId, p.s, obj);
	}
	else {
		console.log("Unknown game progress msg!");
	}
}

function websocketHandleClose() {
	
}

function onGameCardProgress(playerId, slot, progress) {
	var cards = $('#cards div.card[data-pid="' + playerId + '"]');
	
	if (playerId != websocketGame.thisPlayerId) {
		console.log("onGameCardProgress: Opponent's card");
		
		if ( websocketGame.otherPlayerId == 0 ) {
			websocketGame.otherPlayerId = playerId;
		}
		
		//console.log(cards);
		
		if ( is(cards) && is(cards.length) && cards.length > 0 ) {
			console.log("onGameCardProgress: Opponent is already known");
			
			updateCard(cards, slot, progress.cId);
		}
		else {
			console.log("onGameCardProgress: Opponent is NOT known yet");
			
			$('#cards div.card[data-pid="0"]').each(function(index) {
				$(this).attr("data-pid", playerId);
				
				if ( $(this).attr("data-index") == slot ) {
					$(this).attr("data-cid", progress.cId);
					// Update other properties
					setCardImage(this, progress.cId);
				}
			});
		}
	}
	else {
		console.log("onGameCardProgress: This player's card");
		
		updateCard(cards, slot, progress.cId);
	}
}

function updateCard(cards, slot, cId) {
	cards.each(function(index, item) {
		if ( $(item).attr("data-index") == slot ) {
			if ( $(item).attr("data-cid") != cId ) {
				console.log("onGameCardProgress: New card " + cId + " on slot " + slot);
				$(item).attr("data-cid", cId);
				setCardImage(item, cId);
			}
			else {
				console.log("onGameCardProgress: Card didn't changed on slot " + slot);
			}
			// Update other properties
		}
	});
}

function setCardImage(cardItem, cId) {
	if ( cId == -1 ) {
		$(cardItem).find(".back").css('backgroundColor', 'red');
	}
	else {
		var src = websocketGame.cfg.getCardImagePath(cId);
		$(cardItem).find(".back").css('backgroundColor', 'white');
		$(cardItem).find(".back").css('backgroundImage', 'url(' + src +')');
	}
}

function onGameStart() {
	$("#cards").children().each(function(index) {
		$(this).addClass("card-flipped");
	});
}

function is(variable) {
	if (variable != undefined && variable != null) {
		return true;
	}
	else {
		return false;
	}
}

function is_array(o){
	console.log(Object.prototype.toString.call(o));
	
	return Object.prototype.toString.call(o) === '[object Array]';
}
